import { Component, Input, OnInit } from '@angular/core';
import { environment } from '@env/environment';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SystemDictService } from '../../../system/dict/service/service.service';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { BaikeService } from '../service/baike.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styles: [],
})
export class BaikeEditComponent implements OnInit {
  @Input()
  record: any;
  yesOrNo = environment.yesNo;
  form: FormGroup;
  statList: any;
  uploadUrl = environment.uploadUrl;
  previewImage: string | undefined = '';
  previewVisible = false;
  upload = environment.uploadUrl;
  oss: NzUploadFile = {
    uid: '-1',
    name: 'image.png',
    status: 'done',
    url: '',
  };
  constructor(
    private systemDictService: SystemDictService,
    private fb: FormBuilder,
    private modal: NzModalRef,
    private service: BaikeService,
    private message: NzMessageService,
  ) {
    this.form = this.fb.group({
      id: [null],
      name: [null, [Validators.required]],
      description: [null, [Validators.required]],
      content: [null, [Validators.required]],
      animalType: [null, [Validators.required]],
    });
  }

  fileList: NzUploadFile[] = [];

  getBase64(file: File): Promise<string | ArrayBuffer | null> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  }

  handlePreview = async (file: NzUploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj!);
    }
    this.previewImage = file.url || file.preview;
    this.previewVisible = true;
  };

  ngOnInit(): void {
    this.systemDictService.dictList(environment.dict.animalType).subscribe((res) => {
      this.statList = res.data;
    });
    if (this.record) {
      this.oss['url'] = this.record.img;
      this.fileList.push(this.oss);
      this.form.patchValue(this.record);
    }
  }

  save() {
    const isValid = this.validate();
    if (!isValid) {
      this.message.create('error', ' 请填写必填内容！');
      return;
    }
    if (this.fileList.length < 1) {
      this.message.create('error', ' 请上传图片！');
      return;
    }
    const postData = {
      ...this.form.value,
      img: this.fileList[0].thumbUrl,
    };
    this.service.submit(postData).subscribe(() => {
      this.close(true);
    });
  }

  close(fg?: boolean) {
    this.modal.close(fg);
  }

  validate() {
    for (const key in this.form.controls) {
      if (this.form.controls.hasOwnProperty(key)) {
        const element = this.form.controls[key];
        element.markAsDirty();
        element.updateValueAndValidity();
      }
    }
    return this.form.valid;
  }
}
